package com.power.sifa.correction.dao.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.plf.common.utils.CollectionUtil;
import com.plf.core.common.dao.OffersetTransformers;
import com.power.sifa.correction.model.Cre_record_ga;
import com.power.sifa.statistics.model.vo.NightRuleVO;
import org.hibernate.query.internal.NativeQueryImpl;
import org.springframework.stereotype.Repository;
import com.power.sifa.correction.dao.Cre_warning_detailDaoCustom;

import javax.annotation.Resource;
import javax.persistence.Query;
import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* 预警信息违规详情 持久层实现(hibernate)
*/

@Repository
public class Cre_warning_detailDaoImpl implements Cre_warning_detailDaoCustom{

    @Resource
    private EntityManager entityManager;

    @Override
    public NightRuleVO getNightRuleVO(int nightout, Integer gaid) {
        StringBuffer sql = new StringBuffer("select n.name, n.starthm, n.endhm " +
                "from crw_rule_night n " +
                "join cre_warning_detail d on d.ruleid = n.id " +
                "where 1 = 1 ");

        List<Object> paramsList = new ArrayList<>();
        int index = 1;

        if (ObjectUtil.isNotEmpty(nightout)) {
            sql.append(" and d.type = ?" + index++);
            paramsList.add(nightout);
        }

        if (ObjectUtil.isNotEmpty(gaid)) {
            sql.append(" and d.gaid = ?" + index++);
            paramsList.add(gaid);
        }

        Query query = entityManager.createNativeQuery(sql.toString());
        query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);
        for (int i = 0; i <= paramsList.size() - 1; i++) {
            query.setParameter(i + 1, paramsList.get(i));
        }
        List<Map<String, Object>> list = query.getResultList();
        if (ObjectUtil.isEmpty(list)) {
            return null;
        }
        Map<String, Object> map = list.get(0);
        NightRuleVO result = JSON.parseObject(JSON.toJSONString(map), NightRuleVO.class);
        if (ObjectUtil.isEmpty(result)) {
            return null;
        }
        result.setStartTime(map.get("starthm").toString());
        result.setEndTime(map.get("endhm").toString());
        return result;
    }
}